import "package:craze/common/index.dart";
import "package:craze/models/index.dart";
import "package:craze/services/index.dart";
import "package:craze/stores/index.dart";
import "package:flutter/material.dart";
import "package:flutter_screenutil/flutter_screenutil.dart";
import "package:google_fonts/google_fonts.dart";
import 'package:go_router/go_router.dart';

// 他人作品数据模型
// 移除这个自定义类
// class OtherUserPost { ... }

class OtherProfileView extends StatefulWidget {
  final String? userId; // 添加用户ID参数

  const OtherProfileView({super.key, this.userId});

  @override
  State<OtherProfileView> createState() => _OtherProfileViewState();
}

class _OtherProfileViewState extends State<OtherProfileView> {
  // 服务和存储
  final UserService _userService = getIt<UserService>();
  final ShareService _shareService = getIt<ShareService>();
  final AuthStore _authStore = getIt<AuthStore>();
  final CollectionStore _collectionStore = getIt<CollectionStore>();

  // 数据
  UserModel? _otherUser;
  List<SharePostModel> _otherPosts = []; // 修改为SharePostModel
  bool _isFollowing = false;
  bool _isLoading = true;
  String? _errorMessage;
  int _chatCount = 0; // 新增：他人聊天数量

  @override
  void initState() {
    super.initState();
    _loadUserData();
  }

  // 加载用户数据
  Future<void> _loadUserData() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      // 获取用户信息
      if (widget.userId != null) {
        _otherUser = _userService.getUserById(widget.userId!);
      }

      // 如果没有指定用户ID或找不到用户，使用默认用户
      if (_otherUser == null) {
        // 尝试获取第一个非当前用户的用户
        final users = _userService.getAllUsers();
        if (users.isNotEmpty) {
          for (var user in users) {
            if (_authStore.currentUser == null ||
                user.id != _authStore.currentUser!.id) {
              _otherUser = user;
              break;
            }
          }
        }
      }

      // 如果仍然找不到用户，显示错误
      if (_otherUser == null) {
        setState(() {
          _errorMessage = "User not found";
          _isLoading = false;
        });
        return;
      }

      // 检查是否关注了该用户
      if (_authStore.isLoggedIn && _authStore.currentUser != null) {
        _isFollowing = _authStore.currentUser!.followingIds.contains(
          _otherUser!.id,
        );
      }

      // 获取该用户的聊天数量
      _chatCount = getIt<ChatService>().getUserChats(_otherUser!.id).length;

      // 获取用户的分享帖子，直接使用
      _otherPosts = _shareService.getUserShares(_otherUser!.id);

      // 更新收藏状态
      if (_authStore.isLoggedIn && _authStore.currentUser != null) {
        for (var share in _otherPosts) {
          share.isCollected = _collectionStore.isShareInCollection(share.id);
        }
      }
    } catch (e) {
      setState(() {
        _errorMessage = "Failed to load data: ${e.toString()}";
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  // 切换关注状态
  Future<void> _toggleFollow() async {
    if (!_authStore.isLoggedIn ||
        _authStore.currentUser == null ||
        _otherUser == null) {
      // 如果未登录，显示登录对话框
      _showLoginDialog();
      return;
    }

    setState(() {
      _isFollowing = !_isFollowing;
    });

    try {
      if (_isFollowing) {
        await _userService.followUser(
          _authStore.currentUser!.id,
          _otherUser!.id,
        );
      } else {
        await _userService.unfollowUser(
          _authStore.currentUser!.id,
          _otherUser!.id,
        );
      }
      // 不需要更新帖子的关注状态，因为关注状态是用户级别的，不是帖子级别的
      // 移除以下代码块
      /*
      setState(() {
        for (var post in _otherPosts) {
          post = OtherUserPost(
            userName: post.userName,
            userAvatar: post.userAvatar,
            postDate: post.postDate,
            description: post.description,
            images: post.images,
            viewedByAvatars: post.viewedByAvatars,
            viewCount: post.viewCount,
            isBookmarked: post.isBookmarked,
            isFollowing: _isFollowing,
            postId: post.postId,
          );
        }
      });
      */
    } catch (e) {
      // 如果失败，恢复状态
      setState(() {
        _isFollowing = !_isFollowing;
        _errorMessage = "Failed to update follow status: ${e.toString()}";
      });
    }
  }

  // 切换收藏状态
  Future<void> _toggleBookmark(String postId) async {
    if (!_authStore.isLoggedIn || _authStore.currentUser == null) {
      // 如果未登录，显示登录对话框
      _showLoginDialog();
      return;
    }

    // 找到对应的帖子
    final index = _otherPosts.indexWhere((post) => post.id == postId);
    if (index == -1) return;

    // 更新UI状态
    setState(() {
      _otherPosts[index].isCollected = !_otherPosts[index].isCollected;
    });

    try {
      // 更新收藏状态 - 使用正确的toggleShareCollection方法
      await _collectionStore.toggleShareCollection(postId);
    } catch (e) {
      // 如果失败，恢复状态
      setState(() {
        _otherPosts[index].isCollected = !_otherPosts[index].isCollected;
        _errorMessage = "Failed to update bookmark status: ${e.toString()}";
      });
    }
  }

  // 显示登录对话框
  void _showLoginDialog() {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            backgroundColor: MyColors.dark,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16.r),
            ),
            title: Text(
              'Login Required',
              style: TextStyle(
                color: Colors.white,
                fontSize: 18.sp,
                fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
              ),
            ),
            content: Text(
              'You need to login to perform this action.',
              style: TextStyle(
                color: Colors.white,
                fontSize: 14.sp,
                fontFamily: GoogleFonts.inter().fontFamily,
              ),
            ),
            actions: [
              TextButton(
                onPressed: () => context.pop(),
                child: Text(
                  'Cancel',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14.sp,
                    fontFamily: GoogleFonts.inter().fontFamily,
                  ),
                ),
              ),
              TextButton(
                onPressed: () {
                  context.pop();
                  context.push(AppRouter.login);
                },
                child: Text(
                  'Login',
                  style: TextStyle(
                    color: MyColors.blue,
                    fontSize: 14.sp,
                    fontFamily: GoogleFonts.inter().fontFamily,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ],
          ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // 获取他人作品数据 - 直接使用 _otherPosts，不需要类型转换
    final otherPosts = _otherPosts;

    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.commonBg),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          top: false,
          child:
              _isLoading
                  ? _buildLoadingView()
                  : _errorMessage != null
                  ? _buildErrorView()
                  : CustomScrollView(
                    slivers: [
                      // 顶部个人信息区域
                      SliverToBoxAdapter(child: _buildProfileHeader(context)),

                      // 标题
                      SliverPadding(
                        padding: EdgeInsets.fromLTRB(20.w, 20.h, 20.w, 16.h),
                        sliver: SliverToBoxAdapter(
                          child: _buildSectionTitle('Release'),
                        ),
                      ),

                      // 作品列表
                      SliverPadding(
                        padding: EdgeInsets.symmetric(horizontal: 20.w),
                        sliver:
                            otherPosts.isEmpty
                                ? SliverToBoxAdapter(child: _buildEmptyView())
                                : SliverList(
                                  delegate: SliverChildBuilderDelegate((
                                    context,
                                    index,
                                  ) {
                                    return Padding(
                                      padding: EdgeInsets.only(bottom: 20.h),
                                      child: _buildPostItem(otherPosts[index]),
                                    );
                                  }, childCount: otherPosts.length),
                                ),
                      ),

                      // 底部间距
                      SliverToBoxAdapter(child: SizedBox(height: 20.h)),
                    ],
                  ),
        ),
      ),
    );
  }

  // 加载中视图
  Widget _buildLoadingView() {
    return Center(child: CircularProgressIndicator(color: MyColors.blue));
  }

  // 错误视图
  Widget _buildErrorView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.error_outline, color: Colors.white, size: 48.sp),
          SizedBox(height: 16.h),
          Text(
            _errorMessage ?? 'An error occurred',
            style: TextStyle(
              color: Colors.white,
              fontSize: 16.sp,
              fontFamily: GoogleFonts.inter().fontFamily,
            ),
            textAlign: TextAlign.center,
          ),
          SizedBox(height: 24.h),
          ElevatedButton(
            onPressed: _loadUserData,
            style: ElevatedButton.styleFrom(
              backgroundColor: MyColors.blue,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8.r),
              ),
            ),
            child: Text(
              'Retry',
              style: TextStyle(
                color: Colors.white,
                fontSize: 14.sp,
                fontFamily: GoogleFonts.inter().fontFamily,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 顶部个人信息区域
  Widget _buildProfileHeader(BuildContext context) {
    return Stack(
      children: [
        // 背景卡片
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 20.w),
          child: Image.asset(MyImages.mineCard, fit: BoxFit.fill),
        ),

        // 返回按钮
        Positioned(
          top: 56.h,
          left: 20.w,
          child: GestureDetector(
            onTap: () => context.pop(),
            child: Icon(MyIcons.iconBack, color: Colors.white, size: 22.sp),
          ),
        ),

        // 举报按钮
        Positioned(
          top: 52.h,
          right: 20.w,
          child: GestureDetector(
            onTap: () async {
              await ReportDialog.show(
                context,
                title: 'Report',
                description: 'Please select a reason for reporting this user.',
                onSubmit: (type) async {
                  MyToast.showSuccess(context, 'Report successful');
                  GoRouter.of(context).pop();
                },
              );
            },
            child: Icon(MyIcons.iconReport, color: Colors.white, size: 28.sp),
          ),
        ),

        // 用户信息
        Positioned(
          top: 190.h,
          left: 44.w,
          child: Row(
            children: [
              // 头像
              _buildAvatar(
                _otherUser?.avatar.isNotEmpty == true
                    ? _otherUser!.avatar
                    : MyImages.touxiang2,
              ),

              SizedBox(width: 10.w),

              // 用户名和简介
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 用户名
                  Text(
                    _otherUser?.name ?? 'User',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 18.sp,
                      fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                      fontWeight: FontWeight.w400,
                    ),
                  ),

                  SizedBox(height: 9.h),

                  // 用户签名
                  Container(
                    constraints: BoxConstraints(maxWidth: 179.w),
                    child: Text(
                      _otherUser?.description ?? 'No description',
                      style: TextStyle(
                        color: Colors.white.withAlpha(153),
                        fontSize: 14.sp,
                        fontFamily: GoogleFonts.baloo2().fontFamily,
                        fontWeight: FontWeight.w400,
                        height: 1.07,
                      ),
                    ),
                  ),
                ],
              ),

              SizedBox(width: 40.w),

              // 聊天按钮
              GestureDetector(
                onTap: () async {
                  if (!_authStore.isLoggedIn ||
                      _authStore.currentUser == null ||
                      _otherUser == null) {
                    _showLoginDialog();
                    return;
                  }
                  final chatService = getIt<ChatService>();
                  final chat = await chatService.findOrCreatePrivateChat(
                    _authStore.currentUser!.id,
                    _otherUser!.id,
                  );
                  context.push('/chat/${chat.id}');
                },
                child: Container(
                  width: 40.w,
                  height: 40.w,
                  decoration: BoxDecoration(
                    color: MyColors.blue,
                    shape: BoxShape.circle,
                  ),
                  child: Center(
                    child: Icon(
                      MyIcons.iconChat,
                      color: Colors.white,
                      size: 22.sp,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),

        // 用户数据
        Positioned(
          top: 300.h,
          left: 44.w,
          right: 44.w,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              // 关注
              _buildDataItem(
                _otherUser?.followingIds.length.toString() ?? '0',
                'Follow',
              ),
              // 粉丝
              _buildDataItem(
                _otherUser?.followerIds.length.toString() ?? '0',
                'Fan',
              ),
              // 聊天
              _buildDataItem(_chatCount.toString(), 'Chat'),
            ],
          ),
        ),
      ],
    );
  }

  // 用户头像
  Widget _buildAvatar(String imageUrl) {
    return Container(
      width: 60.w,
      height: 60.w,
      decoration: BoxDecoration(
        image: DecorationImage(image: AssetImage(imageUrl), fit: BoxFit.cover),
        shape: BoxShape.circle,
        border: Border.all(color: Colors.white, width: 2.w),
      ),
    );
  }

  // 聊天按钮
  Widget _buildChatButton(bool isFollowing) {
    return Container(
      width: 40.w,
      height: 40.w,
      decoration: BoxDecoration(
        color: isFollowing ? Colors.grey : MyColors.blue,
        shape: BoxShape.circle,
      ),
      child: Center(
        child: Icon(
          isFollowing ? Icons.check : MyIcons.iconAdd,
          color: Colors.white,
          size: 22.sp,
        ),
      ),
    );
  }

  // 数据项
  Widget _buildDataItem(String number, String label) {
    return Builder(
      builder: (context) {
        return Row(
          crossAxisAlignment: CrossAxisAlignment.baseline,
          textBaseline: TextBaseline.alphabetic,
          children: [
            Text(
              number,
              style: TextStyle(
                color: Colors.white,
                fontSize: 18.sp,
                fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                fontWeight: FontWeight.w400,
              ),
            ),
            if (label.isNotEmpty) ...[
              SizedBox(width: 5.w),
              Text(
                label,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14.sp,
                  fontFamily: GoogleFonts.inter().fontFamily,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ],
          ],
        );
      },
    );
  }

  // 标题
  Widget _buildSectionTitle(String title) {
    return Text(
      title,
      style: TextStyle(
        color: Colors.white,
        fontSize: 22.sp,
        fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
        fontWeight: FontWeight.w400,
        height: 1.36,
      ),
    );
  }

  // 空状态视图
  Widget _buildEmptyView() {
    return Column(
      children: [
        SizedBox(height: 30.h),
        Image.asset(MyImages.empty, height: 120.h),
        SizedBox(height: 16.h),
        Text(
          'No posts yet',
          style: TextStyle(
            color: Colors.white,
            fontSize: 16.sp,
            fontFamily: GoogleFonts.inter().fontFamily,
            fontWeight: FontWeight.w500,
          ),
        ),
        SizedBox(height: 8.h),
        Text(
          'This user hasn\'t posted anything yet',
          style: TextStyle(
            color: Colors.white.withAlpha(153),
            fontSize: 14.sp,
            fontFamily: GoogleFonts.inter().fontFamily,
            fontWeight: FontWeight.w400,
          ),
        ),
        // 占位
        SizedBox(height: 200.h),
      ],
    );
  }

  // 作品卡片
  Widget _buildPostItem(SharePostModel post) {
    return Material(
      color: Colors.white.withAlpha(25),
      borderRadius: BorderRadius.circular(16.r),
      child: InkWell(
        onTap: () {
          // 跳转到分享详情页
          GoRouter.of(context).push('/share-detail/${post.id}');
        },
        borderRadius: BorderRadius.circular(16.r),
        child: Padding(
          padding: EdgeInsets.all(14.h),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 顶部作者信息行
              _buildAuthorRow(post),

              SizedBox(height: 12.h),

              // 内容描述
              Text(
                post.description,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14.sp,
                  height: 1.5,
                  fontFamily: GoogleFonts.inter().fontFamily,
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),

              SizedBox(height: 12.h),

              // 图片网格
              _buildImagesGrid(post.imageUrls),

              SizedBox(height: 12.h),

              // 底部操作行
              _buildBottomRow(post),
            ],
          ),
        ),
      ),
    );
  }

  // 作者行
  Widget _buildAuthorRow(SharePostModel post) {
    final userAvatar =
        _otherUser?.avatar.isNotEmpty == true
            ? _otherUser!.avatar
            : MyImages.touxiang2;

    return Row(
      children: [
        // 头像
        GestureDetector(
          onTap: () {
            // 头像点击逻辑 - 这里不需要跳转，因为已经在用户页面
          },
          child: CircleAvatar(
            radius: 22.r,
            backgroundImage: AssetImage(userAvatar),
          ),
        ),

        SizedBox(width: 8.w),

        // 用户名
        Text(
          _otherUser?.name ?? "",
          style: TextStyle(
            color: Colors.white,
            fontSize: 16.sp,
            fontWeight: FontWeight.w400,
            fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
          ),
        ),

        SizedBox(width: 8.w),

        // 关注按钮
        GestureDetector(
          onTap: _toggleFollow,
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
            decoration: BoxDecoration(
              color: _isFollowing ? Colors.grey : MyColors.blue,
              borderRadius: BorderRadius.circular(12.r),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Icon(
                  _isFollowing ? Icons.check : MyIcons.iconAdd,
                  color: Colors.white,
                  size: 12.sp,
                ),
                SizedBox(width: 4.w),
                Text(
                  _isFollowing ? 'following' : 'follow',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 12.sp,
                    fontFamily: GoogleFonts.inter().fontFamily,
                    fontWeight: FontWeight.w700,
                  ),
                ),
              ],
            ),
          ),
        ),

        const Spacer(),

        // 收藏按钮
        GestureDetector(
          onTap: () => _toggleBookmark(post.id),
          child: Container(
            padding: EdgeInsets.all(8.r),
            decoration: BoxDecoration(
              color: MyColors.iconDark,
              shape: BoxShape.circle,
            ),
            child: Icon(
              post.isCollected ? MyIcons.iconCollectFill : MyIcons.iconCollect,
              color: post.isCollected ? MyColors.blue : Colors.white,
              size: 24.sp,
            ),
          ),
        ),
      ],
    );
  }

  // 图片网格
  Widget _buildImagesGrid(List<String> images) {
    return SizedBox(
      height: 113.h,
      child: LayoutBuilder(
        builder: (context, constraints) {
          final imageWidth = (constraints.maxWidth - 16.w) / 3;

          return Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children:
                images.map((image) {
                  return Container(
                    width: imageWidth,
                    height: 113.h,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(12.r),
                      image: DecorationImage(
                        image: AssetImage(image),
                        fit: BoxFit.cover,
                      ),
                    ),
                  );
                }).toList(),
          );
        },
      ),
    );
  }

  // 底部行
  Widget _buildBottomRow(SharePostModel post) {
    // 获取查看者头像
    List<String> viewerAvatars = [];
    for (var viewerId in post.viewerIds) {
      final viewer = _userService.getUserById(viewerId);
      if (viewer != null && viewer.avatar.isNotEmpty) {
        viewerAvatars.add(viewer.avatar);
      } else {
        // 使用默认头像
        viewerAvatars.add(MyImages.touxiang1);
      }
    }

    // 如果没有足够的真实头像，使用默认头像填充
    if (viewerAvatars.isEmpty) {
      viewerAvatars = [
        MyImages.touxiang1,
        MyImages.touxiang3,
        MyImages.touxiang4,
      ];
    }

    return Row(
      children: [
        // 已浏览用户头像
        SizedBox(
          width: 120.w,
          height: 37.h,
          child: Stack(
            children: List.generate(
              viewerAvatars.length > 4 ? 4 : viewerAvatars.length,
              (index) => _buildViewedAvatar(viewerAvatars[index], index),
            ),
          ),
        ),

        SizedBox(width: 4.w),

        // 已查看文本
        Text(
          'Already viewed',
          style: TextStyle(
            color: Colors.white,
            fontSize: 11.sp,
            fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
            fontWeight: FontWeight.w400,
            height: 1.36,
          ),
        ),

        const Spacer(),

        // 举报按钮
        GestureDetector(
          onTap: () async {
            await ReportDialog.show(
              context,
              title: 'Report',
              description: 'Please select a reason for reporting this post.',
              onSubmit: (type) async {
                MyToast.showSuccess(context, 'Report successful');
                await getIt<ShareService>().deleteSharePost(post.id);
                await _loadUserData(); // 新增：刷新作品列表
              },
            );
          },
          child: Container(
            padding: EdgeInsets.all(8.r),
            decoration: BoxDecoration(
              color: MyColors.iconDark,
              shape: BoxShape.circle,
            ),
            child: Icon(MyIcons.iconReport, color: Colors.white, size: 20.sp),
          ),
        ),
      ],
    );
  }

  // 查看头像
  Widget _buildViewedAvatar(String avatarUrl, int index) {
    return Positioned(
      left: index * 25.w,
      child: Container(
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          border: Border.all(color: MyColors.blue, width: 1.w),
        ),
        child: CircleAvatar(
          radius: 18.r,
          backgroundImage: AssetImage(avatarUrl),
        ),
      ),
    );
  }
}
